/**
 * 存储管理模块
 * 用于管理扩展的本地存储
 */

class StorageManager {

  /**
   * 保存API密钥
   * @param {string} apiKey - API密钥
   * @returns {Promise<void>}
   */
  static saveApiKey(apiKey) {
    // 验证参数
    if (!apiKey || typeof apiKey !== 'string') {
      return Promise.reject(new Error('API密钥不能为空且必须是字符串'));
    }
    
    return new Promise((resolve, reject) => {
      try {
        chrome.storage.local.set({ apiKey: apiKey }, () => {
          if (chrome.runtime.lastError) {
            reject(new Error(chrome.runtime.lastError.message));
          } else {
            resolve();
          }
        });
      } catch (e) {
        reject(e);
      }
    });
  }

  /**
   * 获取保存的API密钥
   * @returns {Promise<string|null>}
   */
  static getApiKey() {
    return new Promise((resolve, reject) => {
      try {
        chrome.storage.local.get(['apiKey'], (result) => {
          if (chrome.runtime.lastError) {
            reject(new Error(chrome.runtime.lastError.message));
          } else {
            resolve(result.apiKey || null);
          }
        });
      } catch (e) {
        reject(e);
      }
    });
  }

  /**
   * 保存选中的文本
   * @param {string} text - 选中的文本
   * @returns {Promise<void>}
   */
  static saveSelectedText(text) {
    // 验证参数
    if (typeof text !== 'string') {
      return Promise.reject(new Error('文本必须是字符串'));
    }
    
    return new Promise((resolve, reject) => {
      try {
        chrome.storage.local.set({ selectedText: text }, () => {
          if (chrome.runtime.lastError) {
            reject(new Error(chrome.runtime.lastError.message));
          } else {
            resolve();
          }
        });
      } catch (e) {
        reject(e);
      }
    });
  }

  /**
   * 获取保存的选中文本
   * @returns {Promise<string|null>}
   */
  static getSelectedText() {
    return new Promise((resolve, reject) => {
      try {
        chrome.storage.local.get(['selectedText'], (result) => {
          if (chrome.runtime.lastError) {
            reject(new Error(chrome.runtime.lastError.message));
          } else {
            resolve(result.selectedText || null);
          }
        });
      } catch (e) {
        reject(e);
      }
    });
  }

  /**
   * 清除所有存储的数据
   * @returns {Promise<void>}
   */
  static clearAll() {
    return new Promise((resolve, reject) => {
      try {
        chrome.storage.local.clear(() => {
          if (chrome.runtime.lastError) {
            reject(new Error(chrome.runtime.lastError.message));
          } else {
            resolve();
          }
        });
      } catch (e) {
        reject(e);
      }
    });
  }
}

// 导出StorageManager类
if (typeof module !== 'undefined' && module.exports) {
  module.exports = StorageManager;
} else {
  window.StorageManager = StorageManager;
}